﻿using System;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Web.UI;
using Project.BIZ;
using Project.DTO;
using Project.IBIZ;

namespace Project.UI
{
    public partial class ProductAdd : Page
    {
        /// <summary>
        ///     Global instance from ProductAdd Business layer
        /// </summary>
        private readonly IProductAddBIZ _productAddBiz = new ProductAddBIZ();

        protected void Page_Load(object sender, EventArgs e)
        {
            ddlistCategory.DataSource = _productAddBiz.LoadCategory();
            ddlistCategory.DataTextField = Constants.LoadCategoryName;
            ddlistCategory.DataValueField = Constants.LoadCategoryId;
            ddlistCategory.DataBind();

            ddlistCountry.DataSource = _productAddBiz.LoadCountry();
            ddlistCountry.DataTextField = Constants.LoadCountryName;
            ddlistCountry.DataValueField = Constants.LoadCountryId;
            ddlistCountry.DataBind();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            #region File extension manager

            string[] validFileTypes = {"bmp", "gif", "png", "jpg", "jpeg"};

            string ext = Path.GetExtension(FileUpload1.PostedFile.FileName);

            bool isValidFile = false;

            for (int i = 0; i < validFileTypes.Length; i++)
            {
                if (ext == "." + validFileTypes[i])
                {
                    isValidFile = true;

                    break;
                }
            }

            if (!isValidFile)
            {
                Label1.ForeColor = Color.Red;

                Label1.Text = "Invalid File. Please upload a File with extension " +
                              string.Join(",", validFileTypes);
            }

            else
            {
                Label1.ForeColor = Color.Green;

                Label1.Text = "File uploaded successfully.";
            }

            #endregion

            var product = new Product
            {
                CategoryID = int.Parse(ddlistCategory.SelectedValue),
                ProductName = txtProductName.Text,
                Supplier = txtSupplierName.Text,
                OriginalValue = int.Parse(ddlistCountry.SelectedValue),
                UnitPrice = decimal.Parse(txtUnitPrice.Text),
                Quantity = int.Parse(txtQuantity.Text),
                Description = txtDescription.Text,
                RepresentPicture1 = FileUpload1.PostedFile.FileName,
                RepresentPicture2 = FileUpload2.PostedFile.FileName,
                RepresentPicture3 = FileUpload3.PostedFile.FileName,
                RepresentPicture4 = FileUpload4.PostedFile.FileName,
                RepresentPicture5 = FileUpload5.PostedFile.FileName
            };

            _productAddBiz.AddProduct(product);
        }
    }
}